// 封装一层 aixos
import axios from "axios";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/store/user";
import { logout } from "@/common";

const instance = axios.create({
  baseURL: "/api",
  timeout: 5000,
});

instance.interceptors.request.use(
  (config) => {
    let token = localStorage.getItem("token")
    if (token) {
      if (config.headers) {
        config.headers["Authorization"] = token;
      }
    }
    return config;
  },
  (err) => Promise.reject(err)
);

instance.interceptors.response.use(
  (response) => {
    // 请求成功，但业务失败提示
    const data = response.data as IResponse<any>;
    const store = useUserStore()

    if (data.code === 401) {
      // 退出登录：删token，删动态生成的路由，删仓库数据，提示，跳转到登录页
      logout(undefined, () => {
        ElMessage.error("token过期，请重新登录");
      })
    } else if (data.code !== 200 && data.code) {
      ElMessage.error(data.message)
    }
    return response.data;
  },
  (err) => {
    // 请求失败的提示
    ElMessage.error("请求失败，错误信息:" + err.message)
    Promise.reject(err)
  }
);



export default instance;
